package com.leadingsoft.pwxk.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RequestMapping("api/fileInfo")
@RestController
@Slf4j
public class FileInfoController {

	@Value("${download.oldFile}")
	private String oldFile;

	@Value("${download.newFile}")
	private String newFile;

	@ApiOperation("下载文件")
	@GetMapping(value = "download")
	@ResponseStatus
	public void down(@RequestParam String path, @RequestParam String fileName, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String agent = request.getHeader("USER-AGENT");
			String fileName_ = fileName;
			// IE需要URL编码，chrome，filefox需要ISO8859-1编码
			if (StringUtils.isNoneBlank(agent)) {
				if (StringUtils.containsIgnoreCase(agent, "Trident") || StringUtils.containsIgnoreCase(agent, "MSIE")) {
					fileName_ = URLEncoder.encode(fileName, "UTF-8");
				} else {
					fileName_ = new String(fileName.getBytes(), "ISO8859-1");
				}
			}
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName_);
			try (InputStream iStream = new FileInputStream(getFile(path));
					OutputStream oStream = response.getOutputStream();) {
				IOUtils.copy(iStream, oStream);
			}
		} catch (Exception e) {
			response.setStatus(HttpStatus.NOT_FOUND.value());
			log.error("下载文件时出错", e);
		}
	}

	private File getFile(String fileName) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			File inFile = new File(oldFile + fileName);
			File outFile = new File(newFile);
			if (!outFile.exists()) {
				outFile.mkdirs();
			}
			outFile = new File(outFile, fileName);
			if (outFile.exists() && outFile.isFile()) {
				outFile.delete();
			}

			fis = new FileInputStream(inFile);
			fos = new FileOutputStream(outFile);

			IOUtils.copy(fis, fos);

			return outFile;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(fos);
			IOUtils.closeQuietly(fis);
		}
		return null;
	}
}
